/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年1月24日 下午2:55:02
 */
package com.lenovo.lmrp.server.assigntracer.util.pusher;

import java.util.LinkedList;
import java.util.Objects;
import java.util.regex.Pattern;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lenovo.lmrp.server.assigntracer.scheduler.RetryPushMessageTask;
import com.lenovo.lmrp.server.assigntracer.util.cache.AssignTracerCache;
import com.lenovo.sdc.framework.mq.AMQClient;
import com.lenovo.sdc.framework.scheduler.ScheduleTaskManager;
import com.lenovo.sdc.framework.sns.EMail;
import com.lenovo.sdc.framework.sns.MailSender;
import com.lenovo.sdc.framework.util.AttributeBean;
import com.lenovo.sdc.framework.util.JSONHelper;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * @author songyz
 *
 */
public class EmailSender implements ISender {

    private static final Logger logger = LoggerFactory.getLogger(EmailSender.class);
    private LinkedList<PushParameter> pushParameterList = new LinkedList<PushParameter>();
    private AttributeBean params;
    private MailSender mailSender;
    private AMQClient mqClient;

    @Inject
    public void set(AMQClient mqClient) {
        this.mqClient = mqClient;
    }

    @Inject
    public void set(AttributeBean params) {
        this.params = params;
    }

    @Inject
    public EmailSender(AttributeBean params) {
        this.params = params;
        mailSender = new MailSender(params.getAttribute("email.smtpHost", ""), params.getAttribute("email.user", ""),
            params.getAttribute("email.passwd", ""), Boolean.parseBoolean(params.getAttribute("email.auth", "")));
    }

    public EmailSender() {
    }

    //	public void run() {
    //		PushParameter pushParameter = this.pushParameterList.getFirst();
    //		this.pushParameterList.removeFirst();
    //		SendMessage(pushParameter);
    //	}

    public void SendMessage(PushParameter pushParameter) {

        String[] eamilTo = pushParameter.getEmailAddress().toArray(new String[1]);
        if (eamilTo.length == 1) {
            if (Objects.isNull(eamilTo[0]) || !Pattern.matches(
                "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$", eamilTo[0])) {
                logger.info(
                    "EmailSender send faild. Because the parameter is wrong. emailAddress is :[{}],engineerId is :[{}]",
                    eamilTo[0], pushParameter.getEngineerId());
                return;
            }
        }

        EMail email = new EMail(params.getAttribute("email.user", ""), pushParameter.getTitle(), eamilTo);
        email.setContent(pushParameter.getContent());

        try {
            mailSender.sendMail(email);
            logger.debug("EmailSender send successed.engineerId is :[{}{}] messageContent:{}",
                pushParameter.getEngineerId(),pushParameter.getEmailAddress(), pushParameter.getContent());
            sendMQMessage(mqClient, pushParameter, SendResult.SEND_SUCCEED.getResult());
        }
        catch (Exception e) {
            retryPushMessage(pushParameter);
            throw new TraceableException(ErrorCode.COMM_ERROR, "Email send failed.", e);
        }
    }

    /**
     * 邮件失败重发
     */
    @Override
    public void retryPushMessage(PushParameter pushParameter) {
        logger.debug("EmailSender failed.engineerId is :[{}{}],messageContent:{} ", pushParameter.getEngineerId(),
            pushParameter.getEmailAddress(), pushParameter.getContent());
        sendMQMessage(mqClient, pushParameter, SendResult.SEND_FAILD.getResult());
        RetryPushMessageTask retryEmailMessageTask = new RetryPushMessageTask(pushParameter, params);
        ScheduleTaskManager.getDefaultSchduler().scheduleTask(retryEmailMessageTask);
    }

    public Runnable addMessageToList(PushParameter msParameter) {
        //		this.pushParameterList.addLast(msParameter);
        return new pushMessage(msParameter);
    }

    private class pushMessage implements Runnable {

        private PushParameter msParameter;

        public pushMessage(PushParameter msParameter) {
            this.msParameter = msParameter;
        }

        @Override
        public void run() {
            SendMessage(msParameter);
        }
    }
}
